﻿using System.Collections.Generic;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using ProduceBasicData.Api.DTO;
using ProduceBasicData.Domain.FactoryModeling;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Controllers
{
    /// <summary>
    /// 内部调用客户控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ClientController : ControllerBase
    {
        private readonly IBaseRespository<ClientModel> clientRepo;
        private readonly IConfiguration configuration;

        public ClientController(IBaseRespository<ClientModel> clientRepo,
            IConfiguration configuration)
        {
            this.clientRepo = clientRepo;
            this.configuration = configuration;
        }

        /// <summary>
        /// 内部调用显示客户信息接口
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<List<ClientDTO>>> GetClientServices()
        {
            ApiResult<List<ClientDTO>> res = new ApiResult<List<ClientDTO>>();
            using HttpClient client = new HttpClient();
            var erpurl = configuration.GetValue<string>("ERPBaseUrl");
            client.BaseAddress = new Uri(erpurl);
            var reponse = await client.GetAsync("api/Client/Handle");
            reponse.EnsureSuccessStatusCode();

            var result = await reponse.Content.ReadAsStringAsync();
            var list = JsonConvert.DeserializeObject<ApiResult<List<ClientDTO>>>(result);
            res.Code = ApiEnum.Success;
            res.Msg = "查询成功";
            res.Data = list.Data;
            return res;
        }


        /// <summary>
        /// 内部调用添加客户信息接口
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult<int>> CreateClient()
        {
            ApiResult<int> res = new ApiResult<int>();
            using HttpClient client = new HttpClient();
            //client.BaseAddress = new Uri("http://localhost:8954/");
            var erpurl = configuration.GetValue<string>("ERPBaseUrl");
            client.BaseAddress = new Uri(erpurl);
            var reponse = await client.GetAsync("api/Client/Handle");
            if (reponse.IsSuccessStatusCode)
            {
                var result = await reponse.Content.ReadAsStringAsync();
                var apiResult = JsonConvert.DeserializeObject<ApiResult<List<ClientDTO>>>(result);
                var list = apiResult.Data;

                // 过滤相同信息，避免重复添加
                var filteredList = await FilterDuplicateClients(list);

                var listclient = filteredList.Select(x => new ClientModel()
                {
                    Clientaddr = x.Clientaddr,
                    Clientendtime = x.Clientendtime,
                    Clientname = x.Clientname,
                    Clientnum = x.Clientnum,
                    Clientstarttime = x.Clientstarttime,
                    Clienttel = x.Clienttel,
                    CreateName=x.CreateName,
                    CreateTime=x.CreateTime,
                    States=x.States,
                    Typeid=x.Typeid,
                }).ToList();
                var r=await clientRepo.AddRangeAsync(listclient);
                if (r>0)
                {
                    res.Data = r;
                    res.Msg = "添加成功";
                    res.Code=ApiEnum.Success;
                }
                else
                {
                    res.Msg = "添加失败";
                    res.Code = ApiEnum.Failed;
                }
            }
            return res;
        }

        /// <summary>
        /// 过滤重复的客户信息
        /// </summary>
        /// <param name="clientList">从外部API获取的客户列表</param>
        /// <returns>过滤后的客户列表</returns>
        private async Task<List<ClientDTO>> FilterDuplicateClients(List<ClientDTO> clientList)
        {
            var filteredList = new List<ClientDTO>();
            
            foreach (var client in clientList)
            {
                // 只根据客户名称检查数据库中是否已存在相同的客户信息
                var existingClient = clientRepo.GetAll().FirstOrDefault(x => x.Clientname == client.Clientname);
                
                // 如果不存在，则添加到过滤后的列表中
                if (existingClient == null)
                {
                    filteredList.Add(client);
                }
            }
            
            return filteredList;
        }

    }
}
